package com.shushan.home;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.nearme.game.sdk.GameCenterSDK;
import com.nearme.game.sdk.callback.GameExitCallback;
import com.nearme.game.sdk.common.util.AppUtil;
import com.shushan.base.BaseActivity;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.db.ChildBeanDao;
import com.shushan.home.bean.AppDialogBean;
import com.shushan.home.bean.UpdateBean;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetListCommListener;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DateUtils;
import com.shushan.util.DeviceUtil;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ImageUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.versionupdate.entity.VersionUpdateConfig;
import com.shushan.web.AdvertWebActivity;

import org.json.JSONObject;

import java.util.List;

/**
 * @ClassName: TabHomeActivity
 * @Desciption: 底部tab首页
 * @author: yichaohua
 * @date: 2018-09-12
 */
public class TabHomeActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private static final String TAG = "TabHomeActivity";

    private RadioGroup mHomeRadioGroup;
    private RadioButton mHomeHomeRb;
    private RadioButton mHomeRecordRb;
    private RadioButton mHomeControlRb;
    private RadioButton mHomeMyRb;

    private Dialog vipTimeEndDialog;
    private Dialog advertDialog;

    private FingerprintIdentify mFingerprintIdentify;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private BaseHomeFragment[] mFragments;
    private int mIndex = 0;
    private String versonName;
    private int firstTime = 0;
    private boolean hasOnNewIntent = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_home_activity);
        firstTime = getIntent().getIntExtra("firstTime", 0);
        initView();
        initFragment();
        getUserinfo();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        firstTime = intent.getIntExtra("firstTime", 0);
        if (firstTime == 1) {
            mHomeRadioGroup.check(mHomeHomeRb.getId());
            setIndexSelected(0);
        }
        hasOnNewIntent = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isNotFirstHome = SharedPreferencesUtils.getBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY);
        if (!hasOnNewIntent && isNotFirstHome) {
            if (getPackageName().endsWith(Constants.MASTER_PACKAGE_NAME)) {
                getUpdate();
            } else if (getPackageName().endsWith(Constants.HUAWEI_PACKAGE_NAME)) {
                getAppDialog();
                countActiveUse(DateUtils.getNowDate("yyyyMMdd"));
            }
        }
        SharedPreferencesUtils.setBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY, true);
        hasOnNewIntent = false;
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (advertDialog != null) {
            advertDialog.dismiss();
        }
    }


    private void initView() {
        mHomeRadioGroup = findViewById(R.id.home_radiogroup);  //底部的四个tab
        mHomeHomeRb = findViewById(R.id.home_home_rb);
        mHomeRecordRb = findViewById(R.id.home_record_rb);
        mHomeControlRb = findViewById(R.id.home_control_rb);
        mHomeMyRb = findViewById(R.id.home_my_rb);
        mHomeRadioGroup.setOnCheckedChangeListener(this);
    }

    private void initFragment() {
        //首页
        HomeFragment homeFragment = new HomeFragment();
        //记录
        RecordFragment recordFagment = new RecordFragment();
        //管控
        ParentFragmet parentFragmet = new ParentFragmet();
        //我的
        MineHomeFragment myHomeFagment = new MineHomeFragment();

        //添加到数组
        mFragments = new BaseHomeFragment[]{homeFragment, recordFagment, parentFragmet, myHomeFagment};

        //开启事务
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        //添加首页
        ft.add(R.id.home_content, homeFragment).commit();

        //默认设置为第0个
        setIndexSelected(0);

        boolean isNotFirstHome = SharedPreferencesUtils.getBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY);
        if (!isNotFirstHome) {
            startActivity(ControlGuideActivity.class);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.home_home_rb:
                setIndexSelected(0);
                break;
            case R.id.home_record_rb:
                setIndexSelected(1);
                break;
            case R.id.home_control_rb:
                setIndexSelected(2);
                break;
            case R.id.home_my_rb:
                setIndexSelected(3);
                break;
        }
    }

    private void setIndexSelected(int index) {

        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();


        //隐藏
        ft.hide(mFragments[mIndex]);
        //判断是否添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.home_content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);

            for (int i = 0; i < mFragments.length; i++) {
                if (index == i) {
                    mFragments[i].onFragmentChecked();
                } else {
                    mFragments[i].onFragmentHided();
                }
            }
        }

        ft.commitAllowingStateLoss();
        //再次赋值
        mIndex = index;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_btn_buy_vip:
                startActivity(OpenVipSpendActivity.class);
                if (vipTimeEndDialog != null) {
                    vipTimeEndDialog.dismiss();
                }
                break;
            case R.id.rl_btn_invite:
                startActivity(InviteForFreeUseActivity.class);
                if (vipTimeEndDialog != null) {
                    vipTimeEndDialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    private void getUpdate() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.APP_VERSION);
        urlParse.putValue("system", Constants.OS_TYPE)
                .putValue("version", TextUtils.isEmpty(versonName) ? DeviceUtil.getVersionName(this) : versonName);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UpdateBean>() {

                    @Override
                    protected void onSuccess(UpdateBean userBean) {
                        if (userBean != null) {
                            versonName = userBean.android_version;
                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(
                                    Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);

                            if (isChildControl) {
                                showPswUpdateDialog(userBean);
                            } else {
                                showUpdateDialog(userBean);
                            }

                            countActiveUse(userBean.time);
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        if (netRetBean != null && !TextUtils.isEmpty(netRetBean.getServerData())) {
                            try {
                                JSONObject jsonObject = new JSONObject(netRetBean.getServerData());
                                countActiveUse(jsonObject.optString("time"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        getAppDialog();
                    }

                });
    }

    private void getUserinfo() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_USER_INFO);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if (userBean != null) {
                            int currentId = shuShanApplication.getCurrentChildId();
                            if (currentId > 0 && shuShanApplication.isVip() && (!isFinishing()) && userBean.share_vip_last_time == 1) {
                                showVipTimeEndDialog(userBean.activity_name);
                            }

                            shuShanApplication.setUserBean(userBean);

                            if (!TextUtils.isEmpty(userBean.password)) {
                                SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY, userBean.password);
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if (childList.size() > 0) {
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);
                            } else {
                                new ChildBeanDao(shuShanApplication).clearTab();
                            }

                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }
                });
    }

    private void showVipTimeEndDialog(String activityName) {
        if (vipTimeEndDialog == null) {
            vipTimeEndDialog = new Dialog(this, R.style.Dialog_Translucent_Background);
            vipTimeEndDialog.setContentView(R.layout.dialog_vip_time_end);

            RelativeLayout rlBuyVip = vipTimeEndDialog.findViewById(R.id.rl_btn_buy_vip);
            rlBuyVip.setOnClickListener(this);
            RelativeLayout rlInvite = vipTimeEndDialog.findViewById(R.id.rl_btn_invite);
            rlInvite.setOnClickListener(this);
            if (!TextUtils.isEmpty(activityName)) {
                TextView tvActivityName = vipTimeEndDialog.findViewById(R.id.tv_activity_name);
                tvActivityName.setText(activityName);
            }

            ImageView ivClose = vipTimeEndDialog.findViewById(R.id.iv_close_dialog);
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vipTimeEndDialog.dismiss();
                }
            });

            vipTimeEndDialog.setCancelable(false);
        }

        if (!vipTimeEndDialog.isShowing()) {
            vipTimeEndDialog.show();
        }

    }

    private void showUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this, R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_no_psw_dialog);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);

        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });

        Button btnUpdate = updateDialog.findViewById(R.id.update_dialog_update_btn);
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();

                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(TabHomeActivity.this)//设置上下文
                        .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                        .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                        .setNotificationIconRes(R.drawable.logo)//设置通知图标
                        .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                        .setNotificationTitle("书山宝")//设置通知标题
                        .startDownLoad();//开始下载
            }
        });

        updateDialog.show();
    }

    private void showPswUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this, R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_dialog);
        updateDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);

        final VerificationCodeView veriCodeView = updateDialog.findViewById(R.id.update_dialog_verification_code_view);
        veriCodeView.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {

                if (StringTools.pswValide(content)) {
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(TabHomeActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                } else {
                    showToast("家长密码错误");
                    veriCodeView.clear();
                }
            }
        });

        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                if (mFingerprintIdentify != null) {
                    mFingerprintIdentify.cancelIdentify();
                }
            }
        });

        if (mFingerprintIdentify == null) {
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG, exception.getLocalizedMessage());
                }
            });
        }

        ImageView fingerIconImg = updateDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = updateDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if (mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()) {

            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView) updateDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码进行下载");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(TabHomeActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(TabHomeActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(TabHomeActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(TabHomeActivity.this, R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        } else {
            fingerIconImg.setVisibility(View.GONE);
            ((TextView) updateDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码进行下载");
        }

        updateDialog.show();
    }

    private void countActiveUse(String date) {
        if (TextUtils.isEmpty(date)) {
            return;
        }

        String activieDay = SharedPreferencesUtils.getStringDate(Constants.ACTIVE_USE_DAY_SHAREPREFERS_KEY
                + shuShanApplication.getCurrentChildId());
        String mobile = SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY);
        if (TextUtils.isEmpty(activieDay)) {
            UmengEventUtil.onEvent(shuShanApplication, "users_active_daily_id", mobile);
        } else if (!activieDay.equals(date)) {
            UmengEventUtil.onEvent(shuShanApplication, "users_active_daily_id", mobile);
        }

        SharedPreferencesUtils.setStringDate(Constants.ACTIVE_USE_DAY_SHAREPREFERS_KEY
                + shuShanApplication.getCurrentChildId(), date);
    }

    private void getAppDialog() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.APP_DIALOG);
        urlParse.putValue("user_id", shuShanApplication.getCurrentUseId());

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetListCommListener<AppDialogBean>() {

                    @Override
                    protected void onSuccess(List<AppDialogBean> appDialogBeanList) {
                        if (isForegroud && !ToolUtils.isListEmpty(appDialogBeanList)) {
                            boolean isDialogShow = false;
                            for (int i = 0; i < appDialogBeanList.size(); i++) {
                                AppDialogBean appDialogBean = appDialogBeanList.get(i);
                                if (appDialogBean != null) {
                                    if (DownloadUtil.advertIsExists(appDialogBean.id)) {
                                        String nowDate = DateUtils.getNowDate("yyyyMMdd");
                                        String dayStr = SharedPreferencesUtils.getStringDate(Constants.DIALOG_ONCE_DAY_SHAREPREFERS_KEY
                                                + appDialogBean.id + shuShanApplication.getCurrentChildId());
                                        if (!isDialogShow && (TextUtils.isEmpty(dayStr) || !nowDate.equals(dayStr))) {
                                            isDialogShow = true;
                                            showAdvertDialog(appDialogBean);
                                        }
                                        continue;
                                    } else {
                                        DownloadUtil.downloadAdvertImg(TabHomeActivity.this, appDialogBean);
                                        continue;
                                    }

                                }
                            }
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }

                });
    }

    private void showAdvertDialog(final AppDialogBean appDialogBean) {
        advertDialog = new Dialog(this, R.style.Dialog_Translucent_Background);
        advertDialog.setContentView(R.layout.advert_dialog);

        ImageView imageView = advertDialog.findViewById(R.id.advert_img);
        ImageUtils.loadAdvertNoCacheImg(this, appDialogBean.id, imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                advertDialog.dismiss();

                Intent intent2 = new Intent(TabHomeActivity.this, AdvertWebActivity.class);
                intent2.putExtra("title", appDialogBean.name);
                intent2.putExtra("url", appDialogBean.url);
                startActivityAllow(intent2);
            }
        });

        ImageView ivClose = advertDialog.findViewById(R.id.advert_colse_img);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                advertDialog.dismiss();
            }
        });
        advertDialog.setCancelable(false);

        if (!advertDialog.isShowing()) {
            advertDialog.show();
        }

        String nowDate = DateUtils.getNowDate("yyyyMMdd");
        SharedPreferencesUtils.setStringDate(Constants.DIALOG_ONCE_DAY_SHAREPREFERS_KEY
                + appDialogBean.id + shuShanApplication.getCurrentChildId(), nowDate);
    }

    @Override
    public void onQuitDialogShow() {
        super.onQuitDialogShow();
        if (advertDialog != null) {
            advertDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (vipTimeEndDialog != null) {
            vipTimeEndDialog.dismiss();
        }
        if (mFingerprintIdentify != null) {
            mFingerprintIdentify.cancelIdentify();
        }
    }


    @Override
    public void onBackPressed() {
        if ("oppo".equals(BuildConfig.ENVIRONMENT)) {
            //oppo联运SDK初始化
            GameCenterSDK.getInstance().onExit(TabHomeActivity.this, new GameExitCallback() {
                public void exitGame() {
                    AppUtil.exitGameProcess(TabHomeActivity.this);
                    System.exit(0);
                }
            });
        } else {
            super.onBackPressed();
        }
    }
}
